package com.caiheng.api.service.platfom.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.sys.SysDeptMapper;
import com.caiheng.api.dao.sys.SysUserWxAdminMapper;
import com.caiheng.api.dao.platform.WxTemplateMapper;
import com.caiheng.api.entity.estate.*;
import com.caiheng.api.entity.examine.ExamineApprove;
import com.caiheng.api.entity.examine.ExamineApproveRegAdminRecord;
import com.caiheng.api.entity.examine.ExamineApproveRegRecord;
import com.caiheng.api.entity.examine.ExamineApproveTemplateUser;
import com.caiheng.api.entity.mer.Mer;
import com.caiheng.api.entity.platform.Parameter;
import com.caiheng.api.entity.product.Product;
import com.caiheng.api.entity.product.ProductOrder;
import com.caiheng.api.entity.setmeal.SetMealInfo;
import com.caiheng.api.entity.setmeal.SetMealOrder;
import com.caiheng.api.entity.sys.SysDept;
import com.caiheng.api.entity.sys.SysDeptEventType;
import com.caiheng.api.entity.sys.SysUserWxAdmin;
import com.caiheng.api.entity.wxmsg.*;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.entity.wxuser.UserMp;
import com.caiheng.api.service.estate.EstateUserService;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.platfom.ParameterService;
import com.caiheng.api.service.platfom.WxTemplateService;
import com.caiheng.api.service.product.ProductService;
import com.caiheng.api.service.setmeal.SetMealInfoService;
import com.caiheng.api.service.wxuser.UserMpService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.DateUtil;
import com.caiheng.api.util.MathUtil;
import com.caiheng.api.util.WxMessage;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


@Service
public class WxTemplateServiceImpl extends BaseServiceImpl<WxTemplateMapper, WxTemplate> implements WxTemplateService {

    @Resource
    private UserMpService userMpService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private SysUserWxAdminMapper sysUserWxAdminMapper;
    @Resource
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserService userService;
    @Resource
    private EstateUserService estateUserService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private ProductService productService;
    @Resource
    private SetMealInfoService setMealInfoService;
    @Resource
    private SysDeptMapper sysDeptMapper;

    @Value("${web.appid}")
    private String appid;
    @Value("${web.secret}")
    private String secret;


    @Value("${web.appidWork}")
    private String appidWork;
    @Value("${web.secretWork}")
    private String secretWork;

    @Value("${web.appidMp}")
    private String appidMp;
    @Value("${web.secretMp}")
    private String secretMp;

    @Override
    public int sendWxMsgRefundProduct(User user, ProductOrder order, Integer template_type) {
        try{
            if(order != null){
                String access_token = wxTemplateService.getAccessToken(0);
                //给用户发送支付成功消息
                WxMsgTemplate template = getTemplateToUserByRefund(user,order,template_type);
                String param = JSONUtil.parseObj(template).toString();
                JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
                System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
        return 1;
    }

    /**
     *  发送推送消息到 商家管理员微信上
     * @param user
     * @param order
     * @param template_type
     * @return
     */
    private WxMsgTemplate getTemplateToUserByRefund(User user, ProductOrder order, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        UserMp userMp = userMpService.selectByUniqueColumn("union_id",user.getUnionId());
        if(userMp != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appid);
            miniprogram.put("pagepath","pages/order/productList/index?index=0");
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<>();
//            {{first.DATA}}
//            订单号：{{keyword1.DATA}}
//            商品：{{keyword2.DATA}}
//            退款金额：{{keyword3.DATA}}
//            客户名称：{{keyword4.DATA}}
//            退款原因：{{keyword5.DATA}}
//            {{remark.DATA}}
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("尊敬的用户您好，您的订单已退款完成！");
            m.put("first",first);

            //订单号
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(order.getOrderNo());
            m.put("keyword1",keyword1);

            //商品
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            Product product = productService.getProductByOrderId(order.getId());
            if(product!=null){
                keyword2.setValue(product.getStoreName());
            }else{
                keyword2.setValue("");
            }
            m.put("keyword2",keyword2);


            //退款金额
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(MathUtil.getDoubleUp(order.getRefundPrice().doubleValue())+"");
            m.put("keyword3",keyword3);

            //客户名称
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue(EmojiParser.parseToUnicode(user.getNickName()));
            m.put("keyword4",keyword4);


            //退款原因
            MsgTempData keyword5 = new MsgTempData();
            keyword5.setColor(wxTemplate.getFontColor());
            keyword5.setValue(StrUtil.isNotEmpty(order.getRefundReasonWapExplain())? order.getRefundReasonWapExplain() : "平台退款");
            m.put("keyword5",keyword4);

            //备注信息
            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("感谢您的使用,退款金额以到账为准");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }


    @Override
    public int sendWxMsgRefundSetMeal(User user, SetMealOrder order, Integer template_type) {
        try{
            if(order != null){
                String access_token = wxTemplateService.getAccessToken(0);
                //给用户发送支付成功消息
                WxMsgTemplate template = getTemplateToUserBySetMealRefund(user,order,template_type);
                String param = JSONUtil.parseObj(template).toString();
                JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
                System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
        return 1;
    }


    /**
     *  发送推送消息到 用户微信上
     * @param user
     * @param order
     * @param template_type
     * @return
     */
    private WxMsgTemplate getTemplateToUserBySetMealRefund(User user, SetMealOrder order, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        UserMp userMp = userMpService.selectByUniqueColumn("union_id",user.getUnionId());
        if(userMp != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appid);
            miniprogram.put("pagepath","pages/order/productList/index?index=0");
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("尊敬的用户您好，您的充电套餐订单已退款完成！");
            m.put("first",first);

//            {{first.DATA}}
//            订单号：{{keyword1.DATA}}
//            商品：{{keyword2.DATA}}
//            退款金额：{{keyword3.DATA}}
//            客户名称：{{keyword4.DATA}}
//            退款原因：{{keyword5.DATA}}
//            {{remark.DATA}}

            //订单号
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(order.getOrderNo());
            m.put("keyword1",keyword1);

            //商品
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            SetMealInfo mealInfo = setMealInfoService.findById(order.getMealInfoId());
            if(mealInfo!=null){
                keyword2.setValue(mealInfo.getMealInfoName());
            }else{
                keyword2.setValue("");
            }
            m.put("keyword2",keyword2);


            //退款金额
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(MathUtil.getDoubleUp(order.getRefundPrice().doubleValue())+"");
            m.put("keyword3",keyword3);

            //客户名称
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue(EmojiParser.parseToUnicode(user.getNickName()));
            m.put("keyword4",keyword4);


            //退款原因
            MsgTempData keyword5 = new MsgTempData();
            keyword5.setColor(wxTemplate.getFontColor());
            keyword5.setValue(StrUtil.isNotEmpty(order.getRefundReasonWapExplain())? order.getRefundReasonWapExplain() : "平台退款");
            m.put("keyword5",keyword4);

            //备注信息
            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("感谢您的使用, 退款金额以到账为准");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    @Override
    public int sendWxMsgAddPropertyOrder(User user, PropertyFeeOrder feeOrder) {
        try{
            String access_token = getAccessToken(0);
            QueryWrapper<EstateUser> qw = new QueryWrapper<>();
            //财务部门
            qw.eq("estate_id",feeOrder.getEstateId());
            qw.eq("state",1);
            Integer[] userTypes = { 1, 2,};
            qw.in("user_type", Arrays.asList(userTypes));
            List<EstateUser> list = estateUserService.list(qw);
            if(CollUtil.isNotEmpty(list)){
                for (EstateUser estateUser : list){
                    User userEstate = userService.findById(estateUser.getUserId());
                    if(userEstate != null){
                        //充电开始通知
                        WxMsgTemplate template = getPropertyFeeTemplateToUser(userEstate,feeOrder,10);
                        String param = JSONUtil.parseObj(template).toString();
                        JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
                        System.out.println("公众号推送消息 - 小区客服人员信息:" + jsonObject.toString());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
        return 1;
    }

    /**
     *  开始充电 发给用户的推送消息
     * @param user
     * @param feeOrder
     * @param template_type
     * @return
     */
    private WxMsgTemplate getPropertyFeeTemplateToUser(User user, PropertyFeeOrder feeOrder, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        UserMp userMp = userMpService.selectByUniqueColumn("union_id",user.getUnionId());
        if(userMp != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appid);
            miniprogram.put("pagepath","pagesProperty/pages/propertyList/index");
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<>();
//            {{first.DATA}}
//            房屋住址：{{keyword1.DATA}}
//            物业费用：{{keyword2.DATA}}
//            {{remark.DATA}}
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("尊敬的" + feeOrder.getEstateName()+"管理员您好，有新业主物业订单。");
            m.put("first",first);

            //业主姓名
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(feeOrder.getRoomNo());
            m.put("keyword1",keyword1);

            //地址
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue("请查询后，后台处理");
            m.put("keyword2",keyword2);

            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("业主姓名："+feeOrder.getRealName()+", 联系电话："+feeOrder.getPhoneNum()+",请尽快处理。谢谢。");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    /**
     *  报修成功 公众号推送消息
     * @param repairRecord
     * @return
     */
    @Override
    public int sendWxMsgRepair(RepairRecord repairRecord, int isEnd){
        try{
            Integer template_type = 0;
            String access_token = getAccessToken(0);

//            QueryWrapper<SysDept> qwDept = new QueryWrapper<>();
//            qwDept.eq("estate_id", repairRecord.getEstateId());
//            qwDept.and(wrapper->{
//                wrapper.eq("event_type", 1).or().like("dept_name", "维修");
//            });

            Map<String,Object> map = new HashMap<>();
            map.put("estateId", repairRecord.getEstateId());
            map.put("eventType", 1);
            List<SysDept> deptList = sysDeptMapper.selectDeptListByEstateAndEventType(map);
            if(CollUtil.isNotEmpty(deptList)){
                for (SysDept sysDept : deptList){

                    //给物业经理发通知
                    QueryWrapper<EstateUser> qw = new QueryWrapper<>();
                    qw.eq("estate_id",repairRecord.getEstateId());
                    qw.eq("dept_id", sysDept.getDeptId());
                    qw.eq("state",1);
//                Integer[] ids = {68 ,69};
//                qw.in("id", Arrays.asList(ids));
                    List<EstateUser> list = estateUserService.list(qw);
                    if(CollUtil.isNotEmpty(list)){
                        for (EstateUser estateUser : list){
                            User user1 = userService.findById(estateUser.getUserId());
                            if(user1!=null){
                                UserMp userMp = userMpService.selectByUniqueColumn("union_id",user1.getUnionId());
                                if(userMp != null){
                                    WxMsgTemplate template = null;
                                    if(isEnd == 0){
                                        template_type = 3;
                                        template = getRepairTemplateToManager(userMp,repairRecord,template_type);
                                    }else{
                                        template_type = 4;
                                        template = getRepairEndTemplateToManager(userMp,repairRecord,template_type);
                                    }
                                    String param = JSONUtil.parseObj(template).toString();
                                    System.out.println("请求参数：" + param);
                                    JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
                                    System.out.println("公众号推送消息 - 新报修记录:" + jsonObject.toString());
                                }
                            }
                        }
                    }
                }
            }


            //给维修师傅发通知
//            QueryWrapper<EstateUser> qwWorker = new QueryWrapper<>();
//            qwWorker.eq("estate_id", repairRecord.getEstateId());
//            qwWorker.eq("is_manager", 0);
//            qwWorker.eq("user_type", 0);
//            qwWorker.eq("state",1);
//            List<EstateUser> workers = estateUserService.list(qwWorker);
//            if(CollUtil.isNotEmpty(workers)){
//                for (EstateUser worker : workers){
//                    User user1 = userService.findById(worker.getUserId());
//                    if(user1 != null){
//                        UserMp userMp = userMpService.selectByUniqueColumn("union_id",user1.getUnionId());
//                        if(userMp!=null){
//                            WxMsgTemplate template = null;
//                            if(isEnd == 0){
//                                template_type = 3;
//                                template = getRepairTemplateToManager(userMp,repairRecord,template_type);
//                            }else{
//                                template_type = 4;
//                                template = getRepairEndTemplateToManager(userMp,repairRecord,template_type);
//                            }
//                            String param = JSONUtil.parseObj(template).toString();
//                            JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
//                            System.out.println("公众号推送消息 - 新报修记录:" + jsonObject.toString());
//                        }
//                    }
//                }
//            }


            if(isEnd == 1){
                //给业主发通知
                User user = userService.findById(repairRecord.getUserId());
                UserMp userMp = userMpService.selectByUniqueColumn("union_id",user.getUnionId());
                WxMsgTemplate template = getRepairEndTemplateToUser(userMp, repairRecord,4);
                String param = JSONUtil.parseObj(template).toString();
                JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
                System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
        return 1;
    }


    /**
     *  报修成功 公众号推送消息
     * @param repairRecord
     * @return
     */
    @Override
    public int sendWxMsgRepairToWorker(RepairRecord repairRecord, EstateUser estateUser, int isEnd){
        try{
            int template_type = 3;
            String access_token = getAccessToken(0);
            User user1 = userService.findById(estateUser.getUserId());
            if(user1 != null){
                UserMp userMp = userMpService.selectByUniqueColumn("union_id",user1.getUnionId());
                if(userMp!=null){
                    WxMsgTemplate template = null;
                    if(isEnd == 0){
                        template_type = 3;
                        template = getRepairTemplateToManager(userMp,repairRecord,template_type);
                    }else{
                        template_type = 4;
                        template = getRepairEndTemplateToManager(userMp,repairRecord,template_type);
                    }
                    String param = JSONUtil.parseObj(template).toString();
                    System.out.println("请求参数：" + param);
                    JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
                    System.out.println("公众号推送消息 - 新报修记录:" + jsonObject.toString());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
        return 1;
    }


    /**
     *  发送推送消息到 管理员微信上
     * @param userMp
     * @param repairRecord
     * @param template_type
     * @return
     */
    private WxMsgTemplate getRepairTemplateToManager(UserMp userMp, RepairRecord repairRecord, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        if(wxTemplate != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidWork);// 彩恒云的工作端接收
            miniprogram.put("pagepath","pagesProperty/pages/repair/pick/index");
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<>();
//            报修类型  {{thing8.DATA}}
//            报修地址  {{thing11.DATA}}
//            报修时间  {{time12.DATA}}
//            业主姓名  {{thing16.DATA}}
//            报修问题  {{thing10.DATA}}

            //报修类型
            MsgTempData keyword1 = new MsgTempData();
//            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue("报事报修");
            m.put("thing8",keyword1);

            //报修地址
            MsgTempData keyword2 = new MsgTempData();
//            keyword2.setColor(wxTemplate.getFontColor());
            String roomNo = repairRecord.getEstateName() + repairRecord.getRoomNo();
            if(roomNo.length() > 8){
                roomNo = roomNo.substring(0,8) + "... ";
            }
            keyword2.setValue(roomNo);
            m.put("thing11",keyword2);

            //报修时间
            MsgTempData keyword3 = new MsgTempData();
//            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(DateUtil.getTime(repairRecord.getCreateTime()));
            m.put("time12",keyword3);

            //业主姓名
            MsgTempData keyword4 = new MsgTempData();
//            keyword4.setColor(wxTemplate.getFontColor());
            String name = repairRecord.getNickName() + "("+repairRecord.getPhoneNum()+")";
            if(name.length() > 8){
                name = name.substring(0,8) + "... ";
            }
            keyword4.setValue(name);
            m.put("thing16",keyword4);

            //报修问题
            MsgTempData keyword5 = new MsgTempData();
//            keyword5.setColor(wxTemplate.getFontColor());
            String content = repairRecord.getContent();
            if(content.length() > 8){
                content = content.substring(0,8) + "... ";
            }
            keyword5.setValue(content);
            m.put("thing10",keyword5);


            template.setData(m);
        }
        return template;
    }


    /**
     *  发送推送消息到 管理员微信上
     * @param userMp
     * @param repairRecord
     * @param template_type
     * @return
     */
    private WxMsgTemplate getRepairEndTemplateToManager(UserMp userMp, RepairRecord repairRecord, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        if(wxTemplate!=null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidWork);
            miniprogram.put("pagepath","pagesProperty/pages/repair/info/index?id=" + repairRecord.getId());
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<>();
//            报修单号  {{character_string4.DATA}}
//            报修状态  {{phrase2.DATA}}
//            处理时间  {{time3.DATA}}
//            报修地址  {{thing5.DATA}}
//            维修人员  {{thing6.DATA}}

            //报修单号
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(repairRecord.getRecordNo());
            m.put("character_string4",keyword1);

            //报修状态
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue("处理完成");
            m.put("phrase2",keyword2);

            //处理时间
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(DateUtil.getTime(repairRecord.getOpTime()));
            m.put("time3",keyword3);

            //报修地址
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            String roomNo = repairRecord.getEstateName() + repairRecord.getRoomNo();
            if(roomNo.length() > 8){
                roomNo = roomNo.substring(0,8) + "... ";
            }
            keyword4.setValue(roomNo);
            m.put("thing5",keyword4);

            //维修人员
            MsgTempData keyword5 = new MsgTempData();
            keyword5.setColor(wxTemplate.getFontColor());
            keyword5.setValue(repairRecord.getOpUserName());
            m.put("thing6",keyword5);

            template.setData(m);
        }
        return template;
    }


    /**
     *  发送推送消息到 管理员微信上
     * @param userMp
     * @param repairRecord
     * @param template_type
     * @return
     */
    private WxMsgTemplate getRepairEndTemplateToUser(UserMp userMp, RepairRecord repairRecord, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        if(wxTemplate != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appid);
            miniprogram.put("pagepath","pagesProperty/pages/repair/info/index?id=" + repairRecord.getId());
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<>();
//            报修单号  {{character_string4.DATA}}
//            报修状态  {{phrase2.DATA}}
//            处理时间  {{time3.DATA}}
//            报修地址  {{thing5.DATA}}
//            维修人员  {{thing6.DATA}}

            //报修单号
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(repairRecord.getRecordNo());
            m.put("character_string4",keyword1);

            //报修状态
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue("处理完成");
            m.put("phrase2",keyword2);

            //处理时间
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(DateUtil.getTime(repairRecord.getOpTime()));
            m.put("time3",keyword3);

            //报修地址
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            String roomNo = repairRecord.getEstateName() + repairRecord.getRoomNo();
            if(roomNo.length() > 8){
                roomNo = roomNo.substring(0,8) + "... ";
            }
            keyword4.setValue(roomNo);
            m.put("thing5",keyword4);

            //维修人员
            MsgTempData keyword5 = new MsgTempData();
            keyword5.setColor(wxTemplate.getFontColor());
            keyword5.setValue(repairRecord.getOpUserName());
            m.put("thing6",keyword5);

            template.setData(m);
        }
        return template;
    }

    @Override
    public int sendWxMsgMerRegister(User user, Mer mer) {
        try{
            String access_token = getAccessToken(0);
            QueryWrapper<SysUserWxAdmin> qw = new QueryWrapper<>();
            //市场部门
            qw.eq("dept_id",104);
            qw.eq("state",1);
            List<SysUserWxAdmin> list = sysUserWxAdminMapper.selectList(qw);
            if(CollUtil.isNotEmpty(list)){
                for (SysUserWxAdmin wxAdmin : list){
                    User userAdmin = userService.findById(wxAdmin.getWxUserId());
                    if(userAdmin != null){
                        //商家入驻申请 消息
                        WxMsgTemplate template = getTemplateByMerRegister(userAdmin,mer,20);
                        String param = JSONUtil.parseObj(template).toString();
                        JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
                        System.out.println("公众号推送消息 - 市场人员信息:" + jsonObject.toString());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
        return 1;
    }


    /**
     *  商家入驻申请 消息
     * @param user
     * @param mer
     * @param template_type
     * @return
     */
    private WxMsgTemplate getTemplateByMerRegister(User user, Mer mer, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        UserMp userMp = userMpService.selectByUniqueColumn("union_id",user.getUnionId());
        if(userMp != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

//            Map<String,Object> miniprogram = new HashMap<>();
//            miniprogram.put("appid",appid);
//            miniprogram.put("pagepath","pagesDevice/pages/charger/orderList/index");
//            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<>();
//            {{first.DATA}}
//            联系人：{{keyword1.DATA}}
//            电话号码：{{keyword2.DATA}}
//            公司名称：{{keyword3.DATA}}
//            入驻人数：{{keyword4.DATA}}
//            {{remark.DATA}}
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("来活了，来活了，有新商家入驻申请来啦~");
            m.put("first",first);

            //联系人
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(mer.getLeaderName());
            m.put("keyword1",keyword1);

            //电话号码
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(mer.getTelphone());
            m.put("keyword2",keyword2);

            //公司名称
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(mer.getShopName());
            m.put("keyword3",keyword3);

            //入驻人数
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue("1家");
            m.put("keyword4",keyword4);


            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("请及时审核处理哟~。");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }


    @Override
    public int sendWxMsgEstateChatToManager(EstateChat estateChat) {
        try{
            String access_token = getAccessToken(0);
            //给物业经理发通知
            QueryWrapper<EstateUser> qw = new QueryWrapper<>();
            qw.eq("estate_id",estateChat.getEstateId());
            qw.eq("user_type",2);
            qw.eq("state",1);
            List<EstateUser> list = estateUserService.list(qw);
            if(CollUtil.isNotEmpty(list)){
                for (EstateUser estateUser : list){
                    User user1 = userService.findById(estateUser.getUserId());
                    if(user1!=null){
                        UserMp userMp = userMpService.selectByUniqueColumn("union_id",user1.getUnionId());
                        if(userMp!=null){
                            WxMsgTemplate template = getEstateChatToManager(userMp,estateChat,5);
                            String param = JSONUtil.parseObj(template).toString();
                            JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
                            System.out.println("公众号推送消息 - 新报修记录:" + jsonObject.toString());
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
        return 1;
    }

    /**
     *  推送给物业经理的 推送消息
     * @param userMp
     * @param estateChat
     * @param template_type
     * @return
     */
    private WxMsgTemplate getEstateChatToManager(UserMp userMp , EstateChat estateChat, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        if(userMp != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appid);
            miniprogram.put("pagepath","pagesProperty/pages/chat/index");
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<>();
//            {{first.DATA}}
//            标题：{{keyword1.DATA}}
//            发布时间：{{keyword2.DATA}}
//            内容：{{keyword3.DATA}}
//            {{remark.DATA}}
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("物业经理您好，有业主提出一个新问题~");
            m.put("first",first);

            //标题
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(estateChat.getEstateName() + "业主问题");
            m.put("keyword1",keyword1);

            //发布时间
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(DateUtil.getTime(new Date()));
            m.put("keyword2",keyword2);

            //内容
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(estateChat.getContent());
            m.put("keyword3",keyword3);

            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("请及时回复该业主提出的问题，感谢您的回复。");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }


    @Override
    public int sendWxMsgExamineApprove(ExamineApprove examineApprove, ExamineApproveTemplateUser templateUser, ExamineApproveRegRecord regRecord, ExamineApproveRegAdminRecord adminRecord,int isEnd){
        try {
            String access_token = getAccessToken(0);
            //充电结束通知
            WxMsgTemplate template = getExamineApproveToManager(examineApprove,templateUser,regRecord,adminRecord,isEnd);
            String param = JSONUtil.parseObj(template).toString();
            JSONObject jsonReturn = WxMessage.sendMsg(access_token,param);
            System.out.println("公众号推送消息 - 用户端响应信息:" + jsonReturn.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

    @Override
    public int sendWxMsgExamineApproveToNext(ExamineApprove examineApprove, ExamineApproveTemplateUser templateUser, ExamineApproveRegRecord regRecord, ExamineApproveRegAdminRecord adminRecord, int isEnd) {
        try {
            String access_token = getAccessToken(0);
            //审批推送
            WxMsgTemplate template = getExamineApproveToManager(examineApprove, templateUser, regRecord, adminRecord,isEnd);
            String param = JSONUtil.parseObj(template).toString();
            JSONObject jsonReturn = WxMessage.sendMsg(access_token,param);
            System.out.println("公众号推送消息 - 用户端响应信息:" + jsonReturn.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

    /**
     *  抄送信息
     * @param examineApprove
     * @param templateUser
     * @param adminRecord
     * @return
     */
    private WxMsgTemplate getExamineApproveToManager(ExamineApprove examineApprove, ExamineApproveTemplateUser templateUser, ExamineApproveRegRecord regRecord, ExamineApproveRegAdminRecord adminRecord, int isEnd){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",5);
        UserMp userMp = userMpService.selectByUniqueColumn("union_id", templateUser.getUnionId());
        System.out.println(templateUser.getUserName() +  " unionId " + templateUser.getUnionId());
        if(userMp != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");
            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid", appidWork);
            miniprogram.put("pagepath","pagesProperty/pages/oa/examine/checkdetail/index?id=" + adminRecord.getApproveRecordId());
            template.setMiniprogram(miniprogram);
            Map<String, MsgTempData> m = new HashMap<>();

//            工单名称 {{thing1.DATA}}
//            申请人 {{thing3.DATA}}
//            申请时间  {{time5.DATA}}


            //工单名称
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue(regRecord.getApproveTitle());
            m.put("thing1",first);

            //申请人
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(regRecord.getUserName());
            m.put("thing3",keyword1);

            //申请时间
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(DateUtil.getTime(regRecord.getCreateTime()));
            m.put("time5",keyword2);

            template.setData(m);
        }
        return template;
    }


    @Override
    public int sendWxMsgExamineApproveToUser(ExamineApprove examineApprove, User user, ExamineApproveRegRecord regRecord){
        try {
            String access_token = getAccessToken(0);
            //充电结束通知
            WxMsgTemplate template = getExamineApproveToUser(examineApprove,user,regRecord);
            String param = JSONUtil.parseObj(template).toString();
            JSONObject jsonReturn = WxMessage.sendMsg(access_token,param);
            System.out.println("公众号推送消息 - 用户端响应信息:" + jsonReturn.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

    /**
     *  抄送信息
     * @param examineApprove
     * @param user
     * @param regRecord
     * @return
     */
    private WxMsgTemplate getExamineApproveToUser(ExamineApprove examineApprove, User user, ExamineApproveRegRecord regRecord){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",6);
        UserMp userMp = userMpService.selectByUniqueColumn("union_id",user.getUnionId());
        if(userMp != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");
            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid", appidWork);
            miniprogram.put("pagepath","pagesProperty/pages/oa/examine/detail/index?id=" + regRecord.getId());
            template.setMiniprogram(miniprogram);
            Map<String, MsgTempData> m = new HashMap<>();
//            {{first.DATA}}
//            申请类型：{{keyword1.DATA}}
//            申请时间：{{keyword2.DATA}}
//            审批结果：{{keyword3.DATA}}
//            {{remark.DATA}}

            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue(regRecord.getPropertyName());
            m.put("thing5",first);

            //申请类型
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(examineApprove.getApproveTitle());
            m.put("thing9",keyword1);

            MsgTempData time1 = new MsgTempData();
            time1.setColor(wxTemplate.getSpicalFontColor());
            if(regRecord.getCheckOverTime() != null){
                time1.setValue(DateUtil.getTime(regRecord.getCheckOverTime()));
            }else{
                time1.setValue("");
            }
            m.put("time1",time1);

            template.setData(m);
        }
        return template;
    }


    /**
     * 小程序 订阅 信息
     * @param user
     * @param template_type
     * @param page
     * @param m
     * @return
     */
    private WxSubscribeTemplate getSubscribeMsg(User user, int template_type, String page,Map<String,MsgSubTempData> m){
        WxSubscribeTemplate template = new WxSubscribeTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
//        UserMp userMp = userMpService.selectByUniqueColumn("union_id",user.getUnionId());
//        if(userMp != null){
//        }
        template.setTouser(user.getOpenId());
        template.setTemplate_id(wxTemplate.getTemplateId());
        template.setPage(page);
        template.setData(m);
        return template;
    }


    @Override
    @Transactional
    public String getAccessToken(int type) {
        String access_token = "";
        try{
            Parameter parameter = parameterService.findById(1);
            if(type == 0){//公众号
                access_token = parameter.getAccessTokenMp();
                if(new Date().getTime() > parameter.getAcMpLastTime().getTime()){
                    access_token = WxMessage.getACCESSTOKEN(appidMp,secretMp);
                    parameter.setAccessTokenMp(access_token);
                    //记录2小时之后的时间
                    parameter.setAcMpLastTime(DateUtil.getAfterSecondsByOld(new Date(),7000));
                    parameterService.updateById(parameter);
                }
            }else if(type == 1){//精彩e家小程序
                access_token = parameter.getAccessToken();
                if(new Date().getTime() > parameter.getAcLastTime().getTime()) {
                    access_token = WxMessage.getACCESSTOKEN(appid, secret);
                    parameter.setAccessToken(access_token);
                    parameter.setAcLastTime(DateUtil.getAfterSecondsByOld(new Date(),7000));
                    parameterService.updateById(parameter);
                }
            }else if(type == 2){// 彩恒云 小程序
                access_token = parameter.getAccessTokenWork();
                if(parameter.getAcWorkLastTime()!= null && new Date().getTime() > parameter.getAcWorkLastTime().getTime()) {
                    access_token = WxMessage.getACCESSTOKEN(appidWork, secretWork);
                    parameter.setAccessTokenWork(access_token);
                    parameter.setAcWorkLastTime(DateUtil.getAfterSecondsByOld(new Date(),7000));
                    parameterService.updateById(parameter);
                }else{
                    access_token = WxMessage.getACCESSTOKEN(appidWork, secretWork);
                    parameter.setAccessTokenWork(access_token);
                    parameter.setAcWorkLastTime(DateUtil.getAfterSecondsByOld(new Date(),7000));
                    parameterService.updateById(parameter);
                }
            }
            parameterService.resetParameter(1);
        }catch (Exception e){
            e.printStackTrace();
        }
        return access_token;
    }

}
